package com.hellobike.haxing.modules.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hellobike.haxing.common.util.PasswordUtil;
import com.hellobike.haxing.common.util.oConvertUtils;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClassification;
import com.hellobike.haxing.modules.supplier.entity.TSupplierContract;
import com.hellobike.haxing.modules.supplier.entity.TSupplierInfo;
import com.hellobike.haxing.modules.supplier.mapper.TSupplierInfoMapper;
import com.hellobike.haxing.modules.supplier.service.ITSupplierClassificationService;
import com.hellobike.haxing.modules.supplier.service.ITSupplierContractService;
import com.hellobike.haxing.modules.supplier.service.ITSupplierInfoService;
import com.hellobike.haxing.modules.supplier.util.Constant;
import com.hellobike.haxing.modules.supplier.util.Convert;
import com.hellobike.haxing.modules.system.entity.SysDepartRole;
import com.hellobike.haxing.modules.system.entity.SysUser;
import com.hellobike.haxing.modules.system.entity.SysUserRole;
import com.hellobike.haxing.modules.system.mapper.SysDepartRoleMapper;
import com.hellobike.haxing.modules.system.mapper.SysUserRoleMapper;
import com.hellobike.haxing.modules.system.service.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: t_supplier_info
 * @Author: haxing-boot
 * @Date: 2020-01-13
 * @Version: V1.0
 */
@Service
public class TSupplierInfoServiceImpl extends ServiceImpl<TSupplierInfoMapper, TSupplierInfo> implements ITSupplierInfoService {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private TSupplierInfoMapper supplierInfoMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysDepartRoleMapper sysDepartRoleMapper;

    @Autowired
    private ITSupplierContractService tSupplierContractService;
    @Autowired
    private ITSupplierClassificationService tSupplierClassificationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> saveSupplier(TSupplierInfo tSupplierInfo) {
        Result<?> result = new Result<>();
        SysUser sysUser = sysUserService.getUserByPhone(tSupplierInfo.getMobile());
        if (sysUser != null) {
            return result.error500("手机号已经存在，请更换手机号");
        }
        Integer count = supplierInfoMapper.selectCount(new QueryWrapper<TSupplierInfo>().lambda()
                .eq(TSupplierInfo::getMobile, tSupplierInfo.getMobile()));
        if (count > 1) {
            return result.error500("手机号已经存在，请更换手机号");
        }
        supplierInfoMapper.insert(tSupplierInfo);
        sysUser = new SysUser();
        sysUser.setUsername(tSupplierInfo.getMobile());
        sysUser.setRealname(tSupplierInfo.getRealName());
        if(StringUtils.isBlank(tSupplierInfo.getSupplierPassword())) {
            sysUser.setPassword("123456");
        } else {
            sysUser.setPassword(tSupplierInfo.getSupplierPassword());
        }
        sysUser.setPhone(tSupplierInfo.getMobile());
        sysUser.setStatus(1);
        sysUser.setWorkNo(RandomStringUtils.random(7, false, true));
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), sysUser.getPassword(), salt);
        sysUser.setPassword(passwordEncode);
        sysUserService.save(sysUser);
        List<SysDepartRole> departRoleList = sysDepartRoleMapper
                .selectList(new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId, tSupplierInfo.getDepartId()));
        if (!CollectionUtils.isEmpty(departRoleList)) {
            for (SysDepartRole sysDepartRole : departRoleList) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(sysDepartRole.getRoleId().intValue());
                sysUserRole.setUserId(sysUser.getId());
                sysUserRoleMapper.insert(sysUserRole);
            }
        }

        return result;
    }

    @Override
    public Result<?> editSupplier(TSupplierInfo tSupplierInfo) {
        if (tSupplierInfo.getState() < 3) {
            tSupplierInfo.setState(Constant.INFO_IS_PASS);
        }

        SysUser sysUser = sysUserService.getUserByPhone(tSupplierInfo.getMobile());
        TSupplierInfo origin = supplierInfoMapper.selectById(tSupplierInfo.getId());
        if (origin == null) {
            return Result.error("供应商不存在");
        }
        /**
         * 修改手机，重新创建账号
         */
        if (!origin.getMobile().equals(tSupplierInfo.getMobile())) {
            if (sysUser != null) {
                return Result.error("手机号已经存在，请更换手机号");
            }
            Integer count = supplierInfoMapper.selectCount(new QueryWrapper<TSupplierInfo>().
                    lambda().eq(TSupplierInfo::getMobile, tSupplierInfo.getMobile()));
            if (count > 1) {
                return Result.error("手机号已经存在，请更换手机号");
            }
            sysUser = new SysUser();
            sysUser.setUsername(tSupplierInfo.getMobile());
            if(StringUtils.isBlank(tSupplierInfo.getSupplierPassword())) {
                sysUser.setPassword("123456");
            } else {
                sysUser.setPassword(tSupplierInfo.getSupplierPassword());
            }
            sysUser.setPhone(tSupplierInfo.getMobile());
            sysUser.setStatus(1);
            sysUser.setWorkNo(RandomStringUtils.random(7, false, true));
            sysUser.setRealname(tSupplierInfo.getRealName());
            String salt = oConvertUtils.randomGen(8);
            sysUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), sysUser.getPassword(), salt);
            sysUser.setPassword(passwordEncode);
            sysUserService.save(sysUser);
        }
        if(sysUser == null) {
            sysUser = new SysUser();
            sysUser.setUsername(tSupplierInfo.getMobile());
            if(StringUtils.isBlank(tSupplierInfo.getSupplierPassword())) {
                sysUser.setPassword("123456");
            } else {
                sysUser.setPassword(tSupplierInfo.getSupplierPassword());
            }
            sysUser.setWorkNo(RandomStringUtils.random(7, false, true));
            sysUser.setRealname(tSupplierInfo.getRealName());
            String salt = oConvertUtils.randomGen(8);
            sysUser.setPhone(tSupplierInfo.getMobile());
            sysUser.setStatus(1);
            sysUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), sysUser.getPassword(), salt);
            sysUser.setPassword(passwordEncode);
            sysUserService.save(sysUser);
        }
        /**
         * 删除旧的默认权限
         */
        sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, sysUser.getId()));
        /**
         * 重新授权
         */
        List<SysDepartRole> departRoleList = sysDepartRoleMapper
                .selectList(new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId, tSupplierInfo.getDepartId()));
        if (!CollectionUtils.isEmpty(departRoleList)) {
            for (SysDepartRole sysDepartRole : departRoleList) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(sysDepartRole.getRoleId().intValue());
                sysUserRole.setUserId(sysUser.getId());
                sysUserRoleMapper.insert(sysUserRole);
            }
        }
        tSupplierInfo.setSupplyCategory(Convert.list2Json(tSupplierInfo.getSupplyCategorys()));
        super.updateById(tSupplierInfo);
//		if(tSupplierInfo.getState() != null && tSupplierInfo.getState() == Constant.INFO_IS_PASS){
        if (tSupplierInfo.getState() != null) {
            // 建立初始合同
            QueryWrapper<TSupplierContract> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("supplier_info_id", tSupplierInfo.getId());
            TSupplierContract res = tSupplierContractService.getOne(queryWrapper);
            if (res == null) {
                TSupplierContract tSupplierContract = new TSupplierContract();
                tSupplierContract.setSupplierInfoId(tSupplierInfo.getId());
                tSupplierContract.setSupplierName(tSupplierInfo.getSupplierName());
                tSupplierContract.setState(Constant.CONTRACT_STATE_IS_PASS);
                tSupplierContract.setDeleted(0);
                tSupplierContractService.save(tSupplierContract);
            } else {
                TSupplierContract updateDo = new TSupplierContract();
                updateDo.setId(res.getId());
                updateDo.setSupplierName(tSupplierInfo.getSupplierName());
                tSupplierContractService.updateById(updateDo);
            }
            // 建立初始分类
            QueryWrapper<TSupplierClassification> queryClass = new QueryWrapper<>();
            queryClass.eq("supplier_id", tSupplierInfo.getId());
            TSupplierClassification resClass = tSupplierClassificationService.getOne(queryClass);
            if (resClass == null) {
                TSupplierClassification tSupplierClassification = new TSupplierClassification();
                tSupplierClassification.setSupplierId(tSupplierInfo.getId());
                tSupplierClassification.setSupplierName(tSupplierInfo.getSupplierName());
                tSupplierClassification.setDeleted(0);
                tSupplierClassification.setProvince("[]");
                tSupplierClassification.setCity("[]");
                tSupplierClassification.setFirstCategory("[]");
                tSupplierClassification.setSecondCategory("[]");
                tSupplierClassification.setThirdCategory("[]");
                tSupplierClassification.setWarehouse("[]");
                tSupplierClassificationService.save(tSupplierClassification);
            } else {
                TSupplierClassification updateCl = new TSupplierClassification();
                updateCl.setId(resClass.getId());
                updateCl.setSupplierName(tSupplierInfo.getSupplierName());
                tSupplierClassificationService.updateById(updateCl);
            }


        }
        return Result.ok("编辑成功!");
    }
}
